import axios from 'axios';
import fs from 'fs';
import YAML from 'yaml';
import { generateCookie } from '../../lib/cookie.js';
import { Challenge } from '../../lib/getchallenge.js';
import { processStreamResponse } from './streamResponseProcessor.js'; // 导入新的模块


const FAKE_HEADERS = {
    Accept: "*/*",
    "Accept-Encoding": "gzip, deflate, br, zstd",
    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
    Origin: "https://chat.deepseek.com",
    Pragma: "no-cache",
    Priority: "u=1, i",
    Referer: "https://chat.deepseek.com/",
    "Sec-Ch-Ua": '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
    "Sec-Ch-Ua-Mobile": "?0",
    "Sec-Ch-Ua-Platform": '"Windows"',
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
    "X-App-Version": "20241129.1"
};

/**
 * 聊天功能的主函数
 * @param {string} message - 用户输入的消息
 * @param {string} userID - 用户ID
 * @returns {Promise<object>} - 返回聊天响应的结果
 */
export const chat = async (message, userID) => {
    try {
        let deep = YAML.parse(fs.readFileSync('./plugins/dsplugin-plugin/config/config.yaml', 'utf8'));
        let refreshToken = deep.DEEQSEEKTOKEN;
        if (!refreshToken) return { code: 1, msg: '请先配置DEEQSEEKTOKEN' };
        let cookie = await generateCookie();
        let POW = await Challenge(refreshToken);
        logger.info(POW); // 打印POW
        if (POW.code == 1) {
            return { code: 1, msg: 'token错误或失效，无法获取Challenge' };
        } else {
            const headers = {
                ...FAKE_HEADERS,
                'Cookie': cookie,
                'Authorization': `Bearer ${refreshToken}`,
                'x-ds-pow-response': POW.challenge
            };

            let chatId = await getChatId(userID);
            if (!chatId) {
                chatId = await createChatSession(headers, userID, refreshToken);
            }

            const response = await sendChatMessage(chatId, message, headers, refreshToken);
            const content = await processStreamResponse(response); // 调用新的模块处理返回数据
            await updateMessageId(userID, content.messageId);  // 更新消息ID

            return logger.info(content);
        }
    } catch (error) {
        logger.error(error);
        return { code: 1, msg: '请求失败详细日志请到控制台查看' };
    }
};

/**
 * 获取用户的聊天ID
 * @param {string} userID - 用户ID
 * @returns {Promise<object|null>} - 返回聊天ID对象或null
 */
const getChatId = async (userID) => {
    try {
        const key = await redis.get(`deepseek:chatId:${userID}`);
        return key ? JSON.parse(key) : null;
    } catch (error) {
        logger.error('获取聊天ID失败:', error);
        return;
    }
};

/**
 * 创建新的聊天会话
 * @param {object} headers - 请求头
 * @param {string} userID - 用户ID
 * @returns {Promise<object>} - 返回新创建的聊天会话ID
 */
const createChatSession = async (headers, userID, refreshToken) => {
    try {
        let key = await redis.get(`deepseek:chatId:${userID}`);
        if (key) {
            return JSON.parse(key);
        } else {
            const data = { character_id: null };
            const response = await axios.post('https://chat.deepseek.com/api/v0/chat_session/create', data, { headers });
            if (response.data.code !== 0) {
                logger.error(response.data.message);
                return { code: 1, msg: response.data.message };
            }
            await redis.set(`deepseek:chatId:${userID}`, JSON.stringify({ Id: response.data.data.biz_data.id, message_id: null }));
            return { Id: response.data.data.biz_data.id };
        }
    } catch (error) {
        logger.error('创建聊天会话失败:', error);
        return { code: 1, msg: '创建聊天会话失败' };
    }
};

/**
 * 发送聊天消息
 * @param {string} chatId - 聊天会话ID
 * @param {string} message - 用户输入的消息
 * @param {object} headers - 请求头
 * @returns {Promise} - 返回发送消息的响应
 */
const sendChatMessage = async (chatId, message, headers, refreshToken) => {
    try {
        const data = {
            chat_session_id: chatId.Id,
            parent_message_id: chatId.message_id || null,
            prompt: message,
            ref_file_ids: [],
            thinking_enabled: true,
            search_enabled: false
        };
        let resopen = await axios.post('https://chat.deepseek.com/api/v0/chat/completion', data, { headers, responseType: 'stream' });
        if (resopen.headers["content-type"].indexOf("text/event-stream") === -1) {
            return { code: 1, msg: '服务器返回数据非 text/event-stream' };
        }
        return resopen;
    } catch (error) {
        logger.error('发送聊天消息失败:', error);
        return { code: 1, msg: '发送聊天消息失败' };
    }
};

/**
 * 更新用户的聊天消息ID
 * @param {string} userID - 用户ID
 * @param {string} messageId - 新的消息ID
 */
const updateMessageId = async (userID, messageId) => {
    try {
        logger.info('对话id', messageId);
        let key = await redis.get(`deepseek:chatId:${userID}`);
        let obj = JSON.parse(key || '{}');
        obj.message_id = messageId;
        await redis.set(`deepseek:chatId:${userID}`, JSON.stringify(obj));
    } catch (error) {
        logger.error('更新消息ID失败:', error);
    }
};